package com.core.mvc;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.core.mvc.service.ServiceEngine;

/**
 * Created by yint on 2016/9/28. 入口
 */
public class MainServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	@Override
	public void init( ServletConfig config ) throws ServletException
	{
		super.init( config );
		ServiceEngine.get().startup();
	}

	@Override
	protected void doGet( HttpServletRequest req, HttpServletResponse resp )
					throws ServletException, IOException
	{
		// 分发请求
		ServiceEngine.get().dispatchRequire( getRequestInfo( req, resp ) );
	}

	@Override
	protected void doPost( HttpServletRequest req, HttpServletResponse resp )
					throws ServletException, IOException
	{
		doGet( req, resp );
	}

	/**
	 * 获取请求信息
	 *
	 * @param req请求对象
	 * @param resp应答对象
	 * @return
	 */
	private Require getRequestInfo( HttpServletRequest req, HttpServletResponse resp )
	{
		try
		{
			Require require = new Require();
			String servletPath=req.getServletPath();
			int index = servletPath.lastIndexOf( "/" );
			require.setServiceName( servletPath.substring( 0, index ) );
			require.setActionName( servletPath.substring( index + 1, servletPath.lastIndexOf( "." ) ) );
			require.setType( req.getMethod() );
			require.setReq( req );
			require.setResp( resp );
			return require;
		}
		catch ( Exception e )
		{
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void destroy()
	{
		super.destroy();
	}
}
